package com.funtask.fun.components;

import cn.hutool.core.util.StrUtil;
import com.funtask.fun.entity.UserInfo;
import com.funtask.fun.manager.UserManager;
import com.funtask.fun.utils.JwtTokenUtil;
import com.funtask.fun.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhangqi
 * @date 2024/1/3
 * @time 10:11
 * @description
 */
@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private UserManager userManager;
    @Value("${jwt.tokenKey}")
    private String tokenKey;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        log.info("request:{}",request.getRequestURL());
        String authCode = request.getHeader(tokenKey);
        log.info("authCode:{}",authCode);
        if (StrUtil.isNotBlank(authCode) && authCode.startsWith(tokenHead)) {
            String token = authCode.split(" ")[1];
            Long userId = jwtTokenUtil.getIdFromToken(token);
            log.info("jwtToken userId:{}",userId);
            if (userId != 0 && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserInfo userInfo = userManager.getUserById(userId);
//                if("Y".equals(RedisCacheUtil.getString(memberDo.getXNumber().toString()))){
                MyUserDetails userDetails = new MyUserDetails(userInfo);
                if (jwtTokenUtil.validateToken(token, userId)) {
                    log.info("valid token");
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
//                    }
                };
            }
        }
        chain.doFilter(request,response);

    }
}
